<?php

namespace july\julyadmin\builder\forms;

use july\julyadmin\builder\FormBase;

/**
 * 表单Ueditor组件
 */
class Ueditor extends FormBase
{
    /**
     * 添加组件
     * @Author
     * @DateTime 2023-07-16T12:14:26+0800
     * @param    string                   $field 字段
     * @param    string                   $label 名称
     * @return this
     */
    public function __construct($field = '', $label = '')
    {
        $form              = new \stdClass();
        $form->type        = 'ueditor';
        $form->field       = $field;
        $form->label       = $label;
        $form->placeholder = $label;
        $form->help        = '';
        $form->tips        = ['tips' => '', 'direction' => 2, 'time' => 0, 'background' => '#000000'];
        $form->required    = false;
        $form->width       = '100%';
        $form->height      = '400px';

        //内容
        $form->value   = '';
        $form->default = '';
        $this->form    = $form;

        $this->js = '
            <script type="text/javascript" src="/static/assets/admin/js/ueditor/ueditor.config.js"></script>
            <script type="text/javascript" src="/static/assets/admin/js/ueditor/ueditor.all.min.js"></script>
            <script type="text/javascript" charset="utf-8" src="/static/assets/admin/js/ueditor/lang/zh-cn/zh-cn.js"></script>
        ';
        $this->css = '';
        return $this;
    }

    /**
     * 设置编辑器宽度
     * @Author
     * @DateTime 2023-07-16T12:40:37+0800
     * @param    string                   $width 宽度，可以是具体px值也可以是百分比
     * @return this
     */
    public function width($width = '100%')
    {
        $this->form->width = $width;
        return $this;
    }

    /**
     * 设置编辑器高度
     * @Author
     * @DateTime 2023-07-16T12:41:10+0800
     * @param    string                   $height 高度，可以是具体px值也可以是百分比
     * @return this
     */
    public function height($height = '400px')
    {
        $this->form->height = $height;
        return $this;
    }

    /**
     * 渲染组件
     * @Author
     * @DateTime 2023-07-16T12:22:46+0800
     * @return   array
     */
    public function render()
    {
        $this->form->value = $this->form->default;
        if (isset($this->data[$this->form->field]) && $this->data[$this->form->field] !== "") {
            $this->form->value = $this->data[$this->form->field];
        }

        $required_html = $this->form->required && !$this->isView ? ' <font style="color:red;font-weight:bold;font-size:20px;vertical-align:-webkit-baseline-middle;">*</font>' : '';

        //处理tips
        $tips = '';
        if ($this->form->tips['tips']) {
            $tips = '<font class="form-tips-icon"><i class="mdi mdi-information-outline" tips="' . $this->form->tips['tips'] . '" direction="' . $this->form->tips['direction'] . '" time="' . $this->form->tips['time'] . '" background="' . $this->form->tips['background'] . '" onclick="showTips(this)"></i></font>';
        }

        $this->html .= <<< EOT

        <div class="row ps-0 pe-0 ms-0 me-0 mt-3 mb-3 col-md-{$this->colWidth}">
            <label class="col-sm-{$this->labelWidth} col-form-label pe-2 col-form-label-sm text-sm-end text-md-end text-lg-end text-xl-end">
                {$tips}{$this->form->label}
                {$required_html}
            </label>
EOT;
        $input_html = "";
        if ($this->isView) {
            $input_html .= '<font class="d-flex align-items-center h-100">';
            $input_html .= $this->form->value !== '' ? $this->form->value : '空';
            $input_html .= '</font>';
        } else {
            $input_html = '<textarea id="form-' . $this->form->field . '" name="' . $this->form->field . '" ' . ($this->form->required ? ' required' : '') . ' style="width:' . $this->form->width . ';" ' . $this->readonly . '>' . $this->form->value . '</textarea>';
        }

        //处理help
        if ($this->form->help && !$this->isView) {
            $input_html .= <<<EOT

            <div class="form-help form-text">
                <i class="mdi mdi-information-outline"></i>
                <font>{$this->form->help}</font>
            </div>
EOT;
        }

        $this->html .= <<< EOT

            <div class="col-sm-{$this->inputWidth}">
                {$input_html}
            </div>
        </div>
EOT;
        if (!$this->isView) {
            $app_map = config('app.app_map', []);
            $module = 'admin';
            if ($app_map) {
                if ($key = array_search($module, $app_map)) {
                    $module = $key;
                }
            }
            $serverUrl    = url('/'.$module.'/Ueditor/Index');
            $uploadUrl    = url('/'.$module.'/Files/commonUploadForm');
            $md5          = md5($this->form->field);
            $readonly     = $this->readonly ? 'true' : 'false';
            $this->script = <<<EOT

            <script type="text/javascript">
                window.UEDITOR_HOME_URL = '/static/assets/admin/js/ueditor/';
                var {$this->form->field}_ueditor = UE.getEditor('form-{$this->form->field}',{
                    autoHeightEnabled:false,
                    serverUrl : "{$serverUrl}",
                    uploadImageCallback:'uploadImageCallback_{$md5}',
                    uploadVideoCallback:'uploadVideoCallback_{$md5}',
                    uploadAttachmentsCallback:'uploadAttachmentsCallback_{$md5}',
                    uploadUrl:'{$uploadUrl}',
                    isShow: true,
                    focus: true,
                    enableAutoSave: true,
                    autoSyncData: true,
                    autoFloatEnabled:false,
                    wordCount: true,
                    sourceEditor: null,
                    scaleEnabled:true,
                    height:'{$this->form->height}',
                    readonly:{$readonly}
                });
                {$this->form->field}_ueditor.ready(function () {
                    formValidate(false);
                    this.setHeight(800);
                });

                //图片上传和选择回调
                function uploadImageCallback_{$md5}(urls){
                    var img = {$this->form->field}_ueditor.selection.getRange().getClosedNode();
                    urls.map(item=>{
                        if(img && img.tagName.toLowerCase() == 'img'){
                            //将新图片地址更新上去
                            img.setAttribute('src',item.url);
                            {$this->form->field}_ueditor.execCommand('inserthtml', img.outerHTML);
                        }else{
                            //将图片插入编辑器
                            {$this->form->field}_ueditor.execCommand('insertHTML','<img style="max-width:100%;" src="'+item.url+'"/>');
                        }
                    });
                }

                //视频上传和选择回调
                function uploadVideoCallback_{$md5}(urls){
                    var video = {$this->form->field}_ueditor.selection.getRange().getClosedNode();
                    urls.map(item=>{
                        if(video && video.tagName.toLowerCase() == 'video'){
                            //将视频地址更新上去
                            video.setAttribute('src',item.url);
                            {$this->form->field}_ueditor.execCommand('inserthtml', video.outerHTML);
                        }else{
                            //将视频插入编辑器
                            {$this->form->field}_ueditor.execCommand('insertHTML','<video class="edui-upload-video" controls="" preload="none" width="420" height="280" src="'+item.url+'" data-setup="{}"></video>');
                        }

                    });
                }

                //附件上传和选择回调
                function uploadAttachmentsCallback_{$md5}(urls){
                    var range = {$this->form->field}_ueditor.selection.getRange();
                    var link = range.collapsed ? {$this->form->field}_ueditor.queryCommandValue( "link" ) : {$this->form->field}_ueditor.selection.getStart();
                    var attachment = window.baidu.editor.dom.domUtils.findParentByTagName( link, "a", true );
                    urls.map(item=>{
                        if(attachment){
                            //将附件信息更新上去
                            var obj = {
                                'href' : item.url,
                                'target' : attachment.target,
                                'title' :item.name.replace(/^\s+|\s+$/g, ''),
                                '_href':item.url
                            };
                            range.selectNode(link).select()
                            link[window.baidu.editor.browser.ie ? 'innerText':'textContent'] = item.name;
                            if(range.collapsed){
                                obj.textValue = text.value;
                            }
                            {$this->form->field}_ueditor.execCommand('link',window.baidu.editor.utils.clearEmptyAttrs(obj) );
                        }else{
                            //将附件插入编辑器
                            {$this->form->field}_ueditor.execCommand('insertHTML','<a href="'+item.url+'" title="'+item.name+'">'+item.name+'</a>');
                        }

                    });
                }
            </script>
EOT;
        }

        $result = ['html' => $this->html, 'script' => $this->script, 'js' => $this->js, 'css' => $this->css];
        return $result;
    }
}
